package com.wds.common.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author WDs , wds8.24@outlook.com
 * @version 1.0
 * @since 2022-10-22 19:21
 *
 * Bean属性复制工具类
 */
@Slf4j
public class BeanCopyUtils {

    /**
     * 拷贝属性
     * @param source 源
     * @param targetType 目标类型
     * @return 目标类型 + 源的属性
     */
    public static <V> V copy(Object source, Class<V> targetType) {
        V instance = null;
        try {
            instance = targetType.newInstance();
            //拷贝属性
            BeanUtils.copyProperties(source, instance);
        } catch (Exception e) {
            log.error("error {}", e.getMessage());
        }
        return instance;
    }

    /**
     * 批量拷贝
     */
    public static <V> List<V> copyList(List<?> source, Class<V> targetType) {
        return source.stream().map(
                (item) -> copy(item, targetType)
        ).collect(Collectors.toList());
    }

}
